import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { mobile, device_id, user_id, start_date, end_date } = body

    // 构建查询条件
    const where: any = {
      deleted_at: 0
    }

    if (user_id) {
      where.user_id = user_id
    } else if (mobile) {
      const user = await prisma.smoke_user.findFirst({
        where: {
          mobile: mobile,
          delete_time: 0
        }
      })
      if (!user) {
        return NextResponse.json({
          success: false,
          message: '未找到该手机号对应的用户'
        }, { status: 404 })
      }
      where.user_id = user.id
    }

    if (device_id) {
      where.device_id = device_id
    }

    if (start_date && end_date) {
      where.timestamp = {
        gte: BigInt(new Date(start_date).getTime()),
        lte: BigInt(new Date(end_date).getTime())
      }
    }

    // 按类型统计数据
    const stats = await prisma.yh_logs.groupBy({
      by: ['type'],
      where,
      _count: {
        id: true
      }
    })

    // 获取最新的各类型数据
    const latestData = await Promise.all(
      ['heart_rate', 'hrv', 'spo', 'sleep', 'step'].map(async (type) => {
        const latest = await prisma.yh_logs.findFirst({
          where: {
            ...where,
            type
          },
          orderBy: {
            timestamp: 'desc'
          },
          include: {
            user: {
              select: {
                mobile: true,
                name: true
              }
            }
          }
        })

        if (latest) {
          let parsedData = {}
          try {
            parsedData = JSON.parse(latest.data || '{}')
          } catch (e) {
            parsedData = {}
          }

          return {
            type,
            latest_record: {
              ...latest,
              data: parsedData
            }
          }
        }
        return { type, latest_record: null }
      })
    )

    return NextResponse.json({
      success: true,
      data: {
        statistics: stats,
        latest_data: latestData
      },
      message: '健康数据统计获取成功'
    })
  } catch (error) {
    console.error('Health statistics error:', error)
    return NextResponse.json({
      success: false,
      error: 'Statistics query failed',
      message: '健康数据统计失败'
    }, { status: 500 })
  }
}